package com.zdth.ding.serivce;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.zdth.common.MessageType;
import com.zdth.ding.config.DingKey;
import com.zdth.qywxpush.boot.model.Markdown;
import com.zdth.qywxpush.boot.model.Message;
import com.zdth.wxpush.util.ApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

/**
 * @Author Z-7
 * @Date 2022/9/21
 */
@Slf4j
@Service
public class DingBootPush {
    @Autowired
    private ApiUtil apiUtil;

    public void sendMessage() {
        Long timestamp = System.currentTimeMillis();
        String sign = getSign(timestamp);
        Message message = new Message();
        message.setMsgtype(MessageType.MARKDOWN).setMarkdown(new Markdown("1","![screenshot]("+apiUtil.getPicUrl()+")"));
        String body = HttpRequest.post(DingKey.WEBHOOK + "&timestamp=" + timestamp.toString() + "&sign=" + sign)
                .body(JSONUtil.toJsonStr(message))
                .execute().body();
        log.info("Ding发送结果：{}",body);
    }

    public String getSign(Long timestamp) {
        String stringToSign = timestamp + "\n" + DingKey.SECRET;
        try {
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(DingKey.SECRET.getBytes("UTF-8"), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
            return URLEncoder.encode(new String(Base64.getEncoder().encode(signData)), "UTF-8");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

}
